package com.woniu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.Company1;
import com.woniu.entity.Graduate1;
import com.woniu.entity.Student1;
import com.woniu.pojo.Graduate;
import com.woniu.service.CompanyService;
import com.woniu.service.GraduateService;
import com.woniu.service.StudentService;
import com.woniu.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("graduate")
public class GraduateController {

    @Autowired
    private GraduateService graduateService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CompanyService companyService;

    //增加页面跳转
    @RequestMapping("addJump")
    public String addJump(Model model){
        List<Student1> studentList = studentService.findAll(null);
        List<Company1> companyList = companyService.findAll(null);

        model.addAttribute("studentList",studentList);
        model.addAttribute("companyList",companyList);

        return "WEB-INF/graduate/add";
    }

    //展示页面跳转
    @RequestMapping("listJump")
    public String listJump(){
        return "WEB-INF/graduate/list";
    }

    //增加毕业信息
    @RequestMapping("add")
    @ResponseBody
    public Map<String, Object> add(Graduate graduate){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            graduateService.add(graduate);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return  map;
    }

    //按主键删除毕业信息
    @RequestMapping("deleteById")
    @ResponseBody
    public Map<String,Object> deleteById(Integer graduateId){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            graduateService.deleteById(graduateId);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    //查询一个毕业信息
    @RequestMapping("findOne")
    public Map<String,Object> findOne(Integer graduateId,Model model){
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Graduate1 graduate = graduateService.findOne(graduateId);
            map.put("graduate",graduate);
            map.put("result","ok");
        }catch(Exception e){
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    //跳转到修改
    @RequestMapping("updateJump")
    public String updateJump(Model model, Integer graduateId){
        Graduate1 graduate = graduateService.findOne(graduateId);
        model.addAttribute("graduate",graduate);
        return "WEB-INF/company/update";
    }

    //修改毕业信息
    @RequestMapping("update")
    public Map<String, Object> update(Graduate graduate){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            graduateService.updateById(graduate);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return  map;
    }

    //毕业信息查询分页
    @RequestMapping("findAll")
    @ResponseBody
    public Map<String, Object> findAll(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize",defaultValue ="6") Integer pageSize,Graduate graduate){

        System.out.println("======================================================");
        System.out.println("graduate = " + graduate);
        System.out.println("======================================================");

        Map<String, Object> map=new HashMap<String,Object>();
        try {
            PageHelper.startPage(pageNum,pageSize);
            List<Graduate1> graduateList = graduateService.findAll(graduate);
            List<Student1> studentList = studentService.findAll(null);
            List<Company1> companyList = companyService.findAll(null);

            PageInfo<Graduate1> pageInfo=new PageInfo<Graduate1>(graduateList);

            map.put("pageInfo",pageInfo);
            map.put("graduateList",graduateList);
            map.put("studentList",studentList);
            map.put("companyList",companyList);
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return  map;
    }

    //毕业信息批量删除
    @RequestMapping("deleteByExample")
    @ResponseBody
    public Map<String,Object> deleteByExample(Integer[] graduateIds){
        Map<String, Object> map=new HashMap<String,Object>();
        try {
            graduateService.deleteByExample(Arrays.asList(graduateIds));
            map.put("result","ok");
        } catch (Exception e) {
            map.put("result",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletRequest request,HttpServletResponse response){
        List<Graduate1> graduateList = graduateService.findAll(null);
        String[] title = {"ID","学生","毕业时间","就业公司"};
        String fileName = "graduate.xls";
        String sheetName = "sheet1";
        String[][] content = new String[graduateList.size()][4];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            for (int i = 0;i < graduateList.size();i++){
                content[i][0] = String.valueOf(graduateList.get(i).getGraduateId());
                content[i][1] = graduateList.get(i).getStudentId().getStudentName();
                content[i][2] = sdf.format(graduateList.get(i).getGraduateTime());
                content[i][3] = graduateList.get(0).getCompanyId().getCompanyName();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,title,content,null);
        try {
            this.setResponseHeader(response,fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            fileName = new String(fileName.getBytes(),"utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/importExcel")
    @ResponseBody
    public String importExcel(@RequestParam(value="graduateExcel",required = false)MultipartFile graduateExcel, HttpServletRequest request){
        String flag = "01";// 上传标志
        //导入
        try {
            flag = importExcel123(graduateExcel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public String importExcel123(MultipartFile graduateExcel) throws IOException, InvalidFormatException {
        //获取输入流
        InputStream inputStream = graduateExcel.getInputStream();
        //创建读取工作簿
        Workbook workbook = WorkbookFactory.create(inputStream);
        //获取工作表
        Sheet sheet = workbook.getSheetAt(0);
        //获取总行
        int rows=sheet.getPhysicalNumberOfRows();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(rows>2){
            //获取单元格
            for (int i = 1; i < rows; i++) {
                Row row = sheet.getRow(i);
                Graduate graduate = new Graduate();

                try {
                    String graduateId = row.getCell(0).getStringCellValue();
                    graduate.setGraduateId(Integer.parseInt(graduateId));
                } catch (IllegalStateException e) {
                    int graduateId=(int)row.getCell(0).getNumericCellValue();
                    graduate.setGraduateId(graduateId);
                }

                try {
                    String studentId = row.getCell(1).getStringCellValue();
                    graduate.setStudentId(Integer.parseInt(studentId));
                } catch (IllegalStateException e) {
                    int studentId=(int)row.getCell(1).getNumericCellValue();
                    graduate.setStudentId(studentId);
                }

                try {
                    String graduateTime = row.getCell(2).getStringCellValue();
                    graduate.setGraduateTime(sdf.parse(graduateTime));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                try {
                    String companyId = row.getCell(3).getStringCellValue();
                    graduate.setCompanyId(Integer.parseInt(companyId));
                } catch (IllegalStateException e) {
                    int companyId=(int)row.getCell(3).getNumericCellValue();
                    graduate.setCompanyId(companyId);
                }
                //想数据库中添加新对象
                graduateService.add(graduate);
            }

        }

        inputStream.close();
        return "01";
    }

}




























